package net.mingsoft.basic.util;

import com.alibaba.fastjson.JSONObject;
import net.mingsoft.basic.core.SessionContext;
import net.mingsoft.config.RestTemplateConfig;
import org.slf4j.helpers.MessageFormatter;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

/**
 * @author gengfa
 * @date
 */
public class HttpRequest {

    private HttpRequest() {}

    private static final RestTemplate REST = new RestTemplate();

    private static final RestTemplate UN_SSL_REST = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());

    private static final HttpHeaders HEADER_APPLICATION_JSON = new HttpHeaders();

    static {
        HEADER_APPLICATION_JSON.setContentType(MediaType.APPLICATION_JSON);
    }

    public static HttpEntity<Object> setContType(JSONObject requestBody) {
        return new HttpEntity<>(requestBody.toString(), HEADER_APPLICATION_JSON);
    }

    public static Object post(String url, HttpEntity<Object> entity) {
        return REST.postForObject(url, entity, Object.class);
    }

    public static Object post(String url, HttpHeaders headers, Object obj, Class<?> clazz) {
        return REST.postForObject(url, new HttpEntity<>(obj, headers), clazz);
    }

    public static Object get(String url, HttpHeaders headers, Class<?> clazz) {
        return REST.exchange(url, HttpMethod.GET, new HttpEntity<>(headers), clazz).getBody();
    }

    public static Object postUnSsl(String url, HttpEntity<Object> entity) {
        return UN_SSL_REST.postForObject(url, entity, Object.class);
    }

    public static Object sendBotMsg(String url, String content) {
        JSONObject obj = new JSONObject();
        JSONObject subObj = new JSONObject();

        subObj.put("content", content);
        obj.put("msgtype", "text");
        obj.put("text", subObj);

        return post(url, setContType(obj));
    }
}
